﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace WinApp.Common
{
    public class SocketConnection
    {
        public DateTime LastConnectTime {get; private set;}

        public Socket Connection { get; private set; }

        public SocketConnection(Socket connection)
        {
            Connection = connection;
        }

        public Action<SocketConnection, string> ReceiveNoticeAction;

        public void HandleReceive()
        {
            StringBuilder sb = new StringBuilder();
            while (true)
            {
                if (this.Connection == null)
                {
                    break;
                }              
                
                byte[] buffer = new byte[this.Connection.Available];
                int byteCount = this.Connection.Receive(buffer);                              
                if (byteCount == 0)
                {
                    break;
                }

                this.LastConnectTime = DateTime.Now;

                string receiveData = Encoding.UTF8.GetString(buffer, 0, byteCount);
                if (ReceiveNoticeAction != null)
                {
                    ReceiveNoticeAction(this, receiveData);
                }

                SendData(receiveData);
            }
        }

        private void SendData(string receiveData)
        {
            string sendData = " i know you " + receiveData;

            Connection.Send(Encoding.UTF8.GetBytes(sendData));            
        }        
    }
}
